<template>
  <!-- #ifdef H5 -->
  <template v-if="isH5">
    <Canvas :id="id" class="f2-canvas" type="2d" />
  </template>
  <!-- #endif -->
  <!-- #ifndef H5 -->
  <template v-if="!isH5">
    <canvas :id="id" class="f2-canvas" type="2d" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" />
  </template>
  <!-- #endif -->
</template>

<script setup lang="ts">
import F2 from '@antv/f2'

const props = defineProps({
  appendPadding: {
    type: Object,
    default() {return [5]},
  },
  padding: Object,
  isSyncY: { type: Boolean, default: false },
  animate: { type: Boolean, default: null },
})

const emit = defineEmits(['chart-created'])

let pixelRatio = $ref(1)
const instance = getCurrentInstance()
const timestamp = new Date().getTime()
const id = `f2_id_${timestamp}`
const isH5 = getPlatform() === 'H5'

const wrapEvent = (e) => {
  if (!e) return
  if (!e.preventDefault) {
    e.preventDefault = function () {}
  }
  return e
}

let chart: any = $ref(null)
const canvasEl = $computed(() => {
  return chart.get('el')
})

const touchStart = (e) => {
  const _canvasEl = canvasEl
  if (!_canvasEl) return
  _canvasEl.dispatchEvent('touchstart', wrapEvent(e))
}
const touchMove = (e) => {
  const _canvasEl = canvasEl
  if (!_canvasEl) return
  _canvasEl.dispatchEvent('touchmove', wrapEvent(e))
}
const touchEnd = (e) => {
  const _canvasEl = canvasEl
  if (!_canvasEl) return
  _canvasEl.dispatchEvent('touchend', wrapEvent(e))
}

const createChart = () => {
  if (isNotNilOrEmpty(chart)) return

  // #ifdef MP-WEIXIN
  if (getPlatform() === 'MP-WEIXIN') {
    uni.createSelectorQuery().in(instance).select(`#${id}`)
      .fields({ node: true, size: true }, _ => {})
      .exec((res) => {
        const { node, width, height } = res[0]
        let config = {}
        if (width < 1) return
        const context = node.getContext('2d')
        node.width = width * pixelRatio
        node.height = height * pixelRatio
        config = {
          context, width, height, pixelRatio,
          padding: props.padding, appendPadding: props.appendPadding, syncY: props.isSyncY, animate: props.animate,
        }
        try {
          chart = new F2.Chart(config)
          emit('chart-created', chart)
        } catch (e) {
        // console.log(e)
        }
      })
  }
  // #endif
  // #ifdef H5
  if (getPlatform() === 'H5') {
    uni.createSelectorQuery().in(instance).select(`#${id}`)
      .fields({ scrollOffset: true, size: true }, _ => {})
      .exec((res) => {
        const { width, height } = res[0]
        //  chart全局设置
        let config = {}
        if (width < 1) return
        const el = document.querySelector(`#${id}`)
        config = {
          el, width, height, pixelRatio,
          padding: props.padding, appendPadding: props.appendPadding, syncY: props.isSyncY, animate: props.animate,
        }
        try {
          chart = new F2.Chart(config)
          emit('chart-created', chart)
        } catch (e) {
        // console.log(e)
        }
      })
  }
  // #endif
}

let maxTry = 20 // 最大重试次数
onMounted(() => {
  pixelRatio = uni.getSystemInfoSync().pixelRatio

  let tryTimes = 0 // 当前重试次数
  const createInterval = setInterval(() => {
    try {
      if (isNilOrEmpty(chart) && tryTimes < maxTry) {
        createChart() // 创建图表实例
      } else {
        clearInterval(createInterval) // 清空创建图表实例的定时器
      }
    } catch (e) {
      console.log(e)
    }
    tryTimes++
  }, 200)
})

</script>
